package client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.ResourceBundle;

import javax.swing.JFileChooser;

public class ClientListener extends KeyAdapter implements ActionListener{
	
	private View view;
	Model model;
	DBDialog dbDialog;

    public ClientListener() {
    	view = new DesktopUIView(this);
    }

	public void actionPerformed(ActionEvent e) {
		switch (e.getActionCommand()){
			case "exit":
				view.close();
			break;
			case "openfile":
				JFileChooser chooseFileDialog = new JFileChooser("D://Dev//");
				chooseFileDialog.showOpenDialog(chooseFileDialog);
				File dataFile = chooseFileDialog.getSelectedFile();
				if(dataFile != null){
					String filePath = dataFile.getPath();
					Properties properties = new Properties();
					properties.setProperty("filepath", filePath);
					model = new FileDataModel(properties);
					((Observable)model).addObserver((Observer)view);
				}
			break;
			case "openxml":
				JFileChooser chooseXMLDialog = new JFileChooser("D://Dev//");
				chooseXMLDialog.showOpenDialog(chooseXMLDialog);
				File xmlFile = chooseXMLDialog.getSelectedFile();
				if(xmlFile != null){
					String filePath = xmlFile.getPath();
					Properties properties = new Properties();
					properties.setProperty("filepath", filePath);
					model = new XMLDataModel(properties);
					((Observable)model).addObserver((Observer)view);
				}
			break;
			case "find":
				find();
			break;
			case "opendb":
				Properties properties = new Properties("configs/client/db_conf.xml");
				dbDialog = new DBDialog(properties);
				dbDialog.setVisible(true);
				model = new DBDataModel(dbDialog.getProperties());
				dbDialog.dispose();
				((Observable)model).addObserver((Observer)view);
			break;
			case "network":
				NetworkDialog networkDialog = new NetworkDialog(new Properties("configs/client/client_conf.xml"));
				networkDialog.setVisible(true);
				model = new NetworkDataModel(networkDialog.getProperties());
				((Observable)model).addObserver((Observer)view);
				networkDialog.dispose();
			break;
			case "dbselection_cancelled":
				dbDialog.dispose();
			break;
		}
	}

	@Override
	public void keyPressed(KeyEvent ke) {
		switch (ke.getKeyCode()) {
		case KeyEvent.VK_ENTER :
			find();
			break;
		case KeyEvent.VK_ESCAPE :
			view.close();
			break;
		}
	}
	public void find(){
		model.findText(view.getTextToFind());
	}
}
